package com.miniapp.filter;

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义内容缓存过滤器
 * 用于缓存请求体和响应体，支持多次读取
 * @author author
 * @date 2025-09-01 10:40
 */
public class ContentCachingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        // 包装请求对象，使其支持缓存请求体
        ContentCachingRequestWrapper cachingRequest = new ContentCachingRequestWrapper(request);
        // 包装响应对象，使其支持缓存响应体
        ContentCachingResponseWrapper cachingResponse = new ContentCachingResponseWrapper(response);

        try {
            // 继续过滤器链，使用包装后的请求和响应
            filterChain.doFilter(cachingRequest, cachingResponse);
        } finally {
            // 将缓存的响应体写入原始响应流（必须调用，否则前端无法收到响应）
            cachingResponse.copyBodyToResponse();
        }
    }

    // 可选：指定不需要过滤的路径
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        // 例如：排除静态资源
        return path.startsWith("/static/") || path.endsWith(".js") || path.endsWith(".css");
    }
}

